package com.th.system.service.impl;

import com.th.common.exception.base.BaseException;
import com.th.system.domain.vo.EmailVo;
import com.th.system.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @author ErrorRua
 * @date 2023/07/09
 * @description:
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Value("${spring.mail.sender}")
    private String sender;


    @Override
    public void sendEmail(EmailVo emailVo) {
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            //邮件发件人
            helper.setFrom(sendMailer, sender);
            //邮件收件人
            helper.setTo(emailVo.getEmail());
            //邮件主题
            helper.setSubject(emailVo.getSubject());
            //邮件内容
            helper.setText(emailVo.getText(), true);
            javaMailSender.send(message);
        } catch (MessagingException | UnsupportedEncodingException e) {
            throw new BaseException("邮件发送失败");
        }
    }
}
